$(document).ready(function(){

//弹出框初始化
	var winw = $(window).width();
	var winh = $(window).height();
	var popw = $(".pop_box").width();
	var poph = $(".pop_box").height();
	$(".pop_title").css("width",popw-4);
	var countw = (winw-popw)/2;
	var counth = (winh-poph)/2;
	$(".pop_box").css({"top":counth,"left":countw});
	//弹出层拖拽
	iDrag({
	  target:$('.pop_title'),
	  root: $('.pop_box')
	});


	getLateContact();//获取最近联系人
	getLateGroup();//获取最近联系分组
	// 初始化分页组件
	if(parseInt($("#groupId").val()) !== 0){
		initPagination();
	}
	
	//控制左菜单
	var leftH = $('.main_left').height();
	$('.main').css('min-height',leftH);


//双击最近联系人
$("#lateContact li").live("dblclick", function() {
				var mobile=$(this).attr("title");
				document.location.href=getRootUrl()+"sm/communication/enterEdit?mobile="+mobile;
			});

//双击最近联系分组
$("#lateGroup li").live("dblclick", function() {
				var groupId=$(this).attr("name");
				document.location.href=getRootUrl()+"sm/communication/enterEdit?groupId="+groupId;
			});
			
//初始化最近联系人排序标识			
if($.cookie("Flag_lateContacts_cookie_key")==null)
{
	$.cookie("Flag_lateContacts_cookie_key",1,{expires:7});
}
//初始化最近联系群组排序标识			
if($.cookie("Flag_lateGroup_cookie_key")==null)
{
	$.cookie("Flag_lateGroup_cookie_key",1,{expires:7});
}				
});


// 初始化分页组件
function initPagination() {
	var num_entries = Number($("#totalItemsSize").val());
	var eachPageSize = Number($("#eachPageSize").val());
	var prePage = $("#page").val();
	var current_page_val = 0;
	if (prePage > 1) {
		current_page_val = Number(prePage) - 1;
	}
	if (num_entries > 0) {
		var totalPageVal = parseInt(num_entries / eachPageSize);
		if ((num_entries % eachPageSize) > 0) {
			totalPageVal = totalPageVal + 1;
		}
		if (current_page_val >= totalPageVal) {
			current_page_val = totalPageVal - 1;
		}
		$("#Pagination").pagination(num_entries, {
					num_edge_entries : 1,
					num_display_entries : 3,
					callback : pageselectCallback,
					items_per_page : eachPageSize,
					current_page : current_page_val,
					prev_text : "上一页",
					next_text : "下一页"
				});
	} else {
		loadEachPageAccountItemInfo(1);
		
	}
}

// 分页回调函数
function pageselectCallback(page_index, jq) {
	loadEachPageAccountItemInfo(page_index + 1);
	return false;
}

// 异步加载分页数据
function loadEachPageAccountItemInfo(pageNum) {
	var key = $("#searchKey").val();
	$.ajax({
	   type: "POST",
	   url: "contact/page",
	   data: {
	   		page:pageNum,
	   		groupId:$("#groupId").val(),
	   		key:key
	   	},
	   success: function(html){
	       $("#cont_box_list").html(html);
	       //翻页时，将当前页码数记录到deletePage元素中，在删除的时候会用到该值
	       $("#page").val(pageNum);
	       //如果没有数据就隐藏分页标签
	       if($("#paginationTr").length == 0){
	       		$("#Pagination").hide();
	       }else{
	       		$("#Pagination").show();
	       }
   	   }
	});	 
}

function checkAllOrNot(){
	var checkState = $("#checkAll")[0].checked;
	$("input[name='checks']").each(function(){
		$(this).attr("checked",checkState);
	});
}

//改变群组
function showContactsByGroupId(groupId){
	document.location.href=getRootUrl()+"contact/index?page=1&groupId="+groupId;
}

//用户输入关键字搜索联系人
function searchByKey(){

	if(!checkIshadGroup()){
		alertMsg("请先添加群组!");
		return ;
	}
	$("#searchKey").val($("#searchKeyFirst").val());
	var key = $("#searchKey").val();
	$.ajax({
	   type: "POST",
	   url: "contact/count_contact",
	   data: {
	   		groupId:$("#groupId").val(),
	   		key:key
	   },
	   success: function(data){
		   	if(data.result !== false){
		   	   $("#totalItemsSize").val(data.result);
		       $("#page").val(1);
		       initPagination();
		   	}else{
		   		alertMsg(data.msg);
		   	}
   	   }
	});	
}

function deleteContact(contactId){
	var dialog = art.dialog({
			title : '提示',
			content : "您确定要删除该联系人吗？",
			lock : true,
			drag : false,
			icon : 'question',
			ok : function() {
				//异步删除联系人
				$.ajax({
				   type: "POST",
				   url: "contact/delete_contact",
				   data: {
				   		groupId:$("#groupId").val(),
				   		contactId:contactId
				   },
				   success: function(data){
				   	   if(data.result === true){
				   	   		//删除数据时，分页插件需要在当前页,并计算总共多少条数据
					       $("#totalItemsSize").val($("#totalItemsSize").val()-1); 
					       alertMsg("删除联系人成功！");
					       initPagination();
				   	   }else{
				   	   		alertMsg("删除联系人失败，原因："+data.result);
				   	   }
				   	   
		   	   	  }
				});
				
			},
			cancel : true
	});
}


function batchDeleteContact(){

	if(!checkIshadGroup()){
		alertMsg("请先添加群组!");
		return ;
	}
	var key = $("#searchKey").val();
	var contactIds = new Array();
	$("input[name='checks']").each(function(){
		if($(this).attr("checked")){
			contactIds.push($(this).attr("contactId"));
		}
	});
	
	if(contactIds.length == 0 ){
		alertMsg("请选择一条记录！");
		return;
	}
	
	var dialog = art.dialog({
			title : '提示',
			content : "您确定要删除选中的联系人吗？",
			lock : true,
			drag : false,
			icon : 'question',
			ok : function() {
				$.ajax({
				   type: "POST",
				   url: "contact/batch_delete_contact",
				   data: {
				   		groupId:$("#groupId").val(),
				   		contactIds:contactIds.join(",")
				   },
				   success: function(data){
				   	   if(data.result === true){
				   	   		$.ajax({
							   type: "POST",
							   url: "contact/count_contact",
							   data: {
							   		groupId:$("#groupId").val(),
							   		key:key
							   },
							   success: function(data){ alert(data.result);
							   		if(IsNumber(data.result)){
							   			 $("#totalItemsSize").val(data.result); 
							   			 alertMsg("删除联系人成功!");
				       					 initPagination();
							   		}else{
							   			alertMsg(data.msg);
							   		}
						   	   }
							});	
				   	   }else{
				   	   		alertMsg(data.result);
				   	   }
			   	   }
				});
			},
			cancel : true
		});
}

//添加群组初始化
function addContactGroupInit(showdiv,opcity){
popshow(showdiv,opcity);
$("#groupName").focus();
}
//添加群组
function addContactGroupExe(){
	var groupName =$("#groupName").val();
	var groupTotal =$("#groupTotal").val();//分组总数
	var maxGroups=$("#maxGroups").val();//最大分组数
		if(parseInt(groupTotal)>=parseInt(maxGroups))
		{
			$("#tipMessage").empty().show();
			$("#tipMessage").empty().html("<font color='red'>分组数不可超过"+maxGroups+"个！</font>");
			return false;
		}
		if(trimAllSpace(groupName) == ""){
			$("#tipMessage").empty().show();
			$("#tipMessage").empty().html("<font color='red'>请输入分组名称！</font>");
			$("#groupName").focus();
			return false;
		}
		$.ajax({
		   type: "POST",
		   url: "contact/add_contact_group",
		   data:{
		   		groupName:groupName
		   },
		   success: function(data){
		       if(data.result === true){
		       		document.location.href=getRootUrl()+"contact/index";
		       }else{
		       		//alertMsg(data.result);
		       		$("#tipMessage").empty().show();
					$("#tipMessage").empty().html("<font color='red'>"+data.result+"</font>");
		       }
	   	   }
		});
}

//修改联系群组初始化
function editContactGroupInit(showdiv,opcity,groupId,groupName)
{
	popshow(showdiv,opcity);
	$("#groupNameEdit").val($("#a"+groupId).attr("title"));
	$("#groupIdEdit").val(groupId);
	$("#newGroupName").val($("#a"+groupId).attr("title"));
	$("#newGroupName").focus();
}

function editContactGroupExe(){
	var groupName = $("#groupNameEdit").val();;
	var groupId = $("#groupIdEdit").val();
	var newGroupName =$("#newGroupName").val();
				if(trimAllSpace(newGroupName) == ""){
					$("#tipMessageEdit").empty().show();
					$("#tipMessageEdit").empty().html("<font color='red'>请输入分组名称！</font>");
					$("#newGroupName").focus();
					return false;
				}
				if(newGroupName == groupName){
					$("#tipMessageEdit").empty().show();
				    $("#tipMessageEdit").empty().html("<font color='red'>分组名称未修改！</font>");
					$("#newGroupName").focus();
					return true;
				}
				$.ajax({
				   type: "POST",
				   url: "contact/edit_contact_group",
				   data:{
				   		groupId:groupId,
				   		groupName:newGroupName
				   },
				   success: function(data){
				       if(data.result === true){
				       		$("#a"+groupId).html('<i class="i_f"></i>'+newGroupName);
				       		$("#a"+groupId).attr("title",newGroupName);
				       		$("#edit_group_pop_box").hide();
  							$("#edit_group_opcity").hide();
  							$("#tipMessageEdit").empty().html();
				       		alertMsg("群组修改成功!");
				       }else{
				       		//alertMsg(data.result);
				       		$("#tipMessageEdit").empty().show();
							$("#tipMessageEdit").empty().html("<font color='red'>"+data.result+"</font>");
				       }
			   	   }
				});
}


function deleteContactGroupExe(groupId){
	var dialog = art.dialog({
			title : '提示',
			content : "您确定要删除该群组吗？删除该群组会删除该群组下所有联系人！",
			lock : true,
			drag : false,
			icon : 'question',
			ok : function() {
				//异步删除群组
				$.ajax({
				   type: "POST",
				   url: "contact/delete_contact_group",
				   data:{
				   		groupId:groupId
				   },
				   success: function(data){
				       if(data.result == true){
				       		$("#li"+groupId).remove();
				       		document.location.href=getRootUrl()+"contact/index"
				       		//alertMsg("群组删除成功!");
				       }else{
				       		alertMsg(data.result);
				       }
			   	   }
				});
				
			},
			cancel : true
	});
}

//添加联系人初始化
function addContactInit(showdiv,opcity){
if(!checkIshadGroup()){
		alertMsg("请先添加群组!");
		return ;
	}
popshow(showdiv,opcity);
$("#contactRealName").focus();
}


function addContactExe(){
	$("#tipMessageContact").show();
	if(!checkIshadGroup()){
		//alertMsg("请先添加群组!");
		$("#tipMessageContact").empty().html("<font color='red'>请先添加群组！</font>");
		return ;
	}
	var contactName = $("#contactRealName").val();
	var contactMsisdn = $("#contactMsisdn").val();
	
	if(trimAllSpace(contactName) == ""){
		$("#tipMessageContact").empty().html("<font color='red'>请输入联系人姓名！</font>");
		$("#contactRealName").focus();
		return false;
	}
	if(trimAllSpace(contactMsisdn) == ""){
		$("#tipMessageContact").empty().html("<font color='red'>联系人手机号码不能为空！</font>");
		$("#contactMsisdn").focus();
		return false;
	}
	if(!isMobilePhone(contactMsisdn)){
		$("#tipMessageContact").empty().html("<font color='red'>请填写正确的手机号码！</font>");
		$("#contactMsisdn").focus();
		return false;
	}
	$.ajax({
	   type: "POST",
	   url: "contact/add_contact",
	   dataType: 'json',
	   data: JSON.stringify({name:contactName,msisdn:contactMsisdn,groupId:$("#groupId").val()}),
	   contentType:'application/json;charset=UTF-8',
	   success: function(data){
	   		if(data.result === true){
	   			$("#totalItemsSize").val(parseInt($("#totalItemsSize").val())+1); 
	   			$("#page").val(1);
	   			$("#contactRealName").val("");
				$("#contactMsisdn").val("");
	   			$("#add_contact_pop_box").hide();
   				$("#add_contact_opcity").hide();
   				$("#tipMessageContact").hide();
	   			alertMsg("联系人添加成功!");
		        initPagination();
	   		}else{
	   			//alertMsg(data.result);
	   			$("#tipMessageContact").empty().show();
				$("#tipMessageContact").empty().html("<font color='red'>"+data.result+"</font>");
	   		}
   	   }
	});	

}

//修改联系人初始化
function editContactInit(contactId){
	$("#edit_contact_pop_box").show();
	$("#edit_contact_opcity").show();
	var name = $("#contact_"+contactId).attr("contactName");
	var msisdn = $("#contact_"+contactId).attr("contactMsisdn");
	$("#contactIdEdit").val(contactId);
	$("#contactNameEdit").val(name);
	$("#contactMsisdnEdit").val(msisdn);
	$("#oldContactNameEdit").val(name);
	$("#oldContactMsisdnEdit").val(msisdn);
	$("#contactNameEdit").focus();
}

function editContactExe(){
		var name= $("#oldContactNameEdit").val();
		var msisdn= $("#oldContactMsisdnEdit").val();
		var contactId = $("#contactIdEdit").val();
		var contactName = $("#contactNameEdit").val();
		var contactMsisdn = $("#contactMsisdnEdit").val();
		if(trimAllSpace(contactName) == ""){
			$("#tipMessageContactEdit").show();
			$("#tipMessageContactEdit").empty().html("<font color='red'>请输入联系人姓名！</font>");
			$("#contactNameEdit").focus();
			return false;
		}
		if(trimAllSpace(contactMsisdn) == ""){
			$("#tipMessageContactEdit").show();
			$("#tipMessageContactEdit").empty().html("<font color='red'>联系人手机号码不能为空！</font>");
			$("#contactMsisdnEdit").focus();
			return false;
		}
		if(!isMobilePhone(contactMsisdn)){
			$("#tipMessageContactEdit").show();
			$("#tipMessageContactEdit").empty().html("<font color='red'>请填写正确的手机号码！</font>");
			$("#contactMsisdnEdit").focus();
			return false;
		}
		if(name == contactName && msisdn == contactMsisdn){
			$("#tipMessageContactEdit").show();
			$("#tipMessageContactEdit").empty().html("<font color='red'>联系人信息未修改！</font>");
			$("#contactNameEdit").focus();
			return true;
		}
		$.ajax({
		   type: "POST",
		   url: "contact/edit_contact",
		   dataType: 'json',
		   data: JSON.stringify({id:contactId,name:contactName,msisdn:contactMsisdn,groupId:$("#groupId").val()}),
		   contentType:'application/json;charset=UTF-8',
		   success: function(data){
		   		if(data.result === true){
					$("#contact_"+contactId).attr("contactName",contactName);
	          		$("#contact_"+contactId).attr("contactMsisdn",contactMsisdn);
	          		$("#edit_contact_pop_box").hide();
	          		$("#edit_contact_opcity").hide();
	          		$("#tipMessageContactEdit").hide();
					alertMsg("联系人修改成功!");
			        initPagination();
		   		}else{
		   			//alertMsg(data.result);
		   			$("#tipMessageContactEdit").empty().show();
					$("#tipMessageContactEdit").empty().html("<font color='red'>"+data.result+"</font>");
		   		}
	   	   }
		});	
}

function contactImport(){
		if(!checkIshadGroup()){
			alertMsg("请先添加群组!");
			return ;
		}
		
		var key = $("#searchKey").val();
		document.location.href = getRootUrl()+"contact/contact_import?page="+$("#page").val()+"&groupId="+$("#groupId").val()+"&key="+key;
}

function checkIshadGroup(){
	var groupId = $("#groupId").val();
	if(parseInt(groupId) == 0){
		return false;
	}else{
		return true;
	}
}

//获取最近联系人
function getLateContact()
{
	$.post("contact/lateContact", {
			}, function(data) {
				$("#lateContact").html(data);
			});
}

//获取最近联系分组
function getLateGroup()
{
	$.post("contact/lateGroup", {
			}, function(data) {
				$("#lateGroup").html(data);
			});
}


//联系人批量发送短信
function batchSendMsg(){
	var contactIds = new Array();
	$("input[name='checks']").each(function(){
		if($(this).attr("checked")){
			contactIds.push($(this).attr("contactMsisdn"));
			
			var obj = new Object();
            obj.msisdn = $(this).attr("contactMsisdn");
            obj.name = $(this).attr("contactName");
            obj.id = parseInt($.cookie("Flag_lateContacts_cookie_key"));//仅用于排序的标识
            $.cookie("Flag_lateContacts_cookie_key",parseInt($.cookie("Flag_lateContacts_cookie_key"))+1,{expires:7})
            var objString = JSON.stringify(obj); //JSON 数据转化成字符串
            $.removeCookie("C_lateContacts_cookie_key"+$(this).attr("contactMsisdn"));
            $.cookie("C_lateContacts_cookie_key"+$(this).attr("contactMsisdn"),objString,{expires:7});
		}
	});

	if(contactIds.length == 0 ){
		alertMsg("请选择联系人！");
		return;
	}

	document.location.href=getRootUrl()+"sm/communication/enterEdit?mobile="+contactIds;
}


//群组批量发送短信
function groupBatchSendMsg(groupId,groupName){
	var obj = new Object();
     obj.id = groupId;
     obj.name = $("#groupName"+groupId).attr("contactGroup");
     obj.contactsNum = parseInt($.cookie("Flag_lateGroup_cookie_key"));//仅用于排序的标识
     $.cookie("Flag_lateGroup_cookie_key",parseInt($.cookie("Flag_lateGroup_cookie_key"))+1,{expires:7})
     var objString = JSON.stringify(obj); //JSON 数据转化成字符串
     $.removeCookie("G_lateContacts_cookie_key"+groupId);
     $.cookie("G_lateContacts_cookie_key"+groupId,objString,{expires:7});
	document.location.href=getRootUrl()+'sm/communication/enterEdit?groupId='+groupId;
}
//pop
function popshow(showdiv,opcity)
{
   $("#"+showdiv).show();
   $("#"+opcity).show();
}
function pophide(showdiv,opcity,tip)
{
   $("#"+showdiv).hide();
   $("#"+opcity).hide();
   $("#"+tip).hide();
}